<template>
  <div class="service-record" v-loading="loadPage">
    <template v-if="!loadPage">
      <template
        v-if="showCard"
      >
        <el-card class="session-card" shadow="hover">
          <div slot="header" @click="expand('session')">
            <span
            ><i
              class="iconfont icon-nav-down toggle-up"
              :class="sessionToggle ? 'is-reverse' : ''"
            ></i
            >{{ `${$t('im.imChat.components.seviceRecords.des1')}(${serviceList.length})` }}</span
            >
          </div>
          <div class="list-wrap">
            <div
              v-show="showSession"
              v-for="item in serviceList"
              :key="item.id"
              class="list-item"
              @click="goImDetail(item.id)"
            >
              <div class="list-content">
                <div class="form-view-row">
                  <label>{{$t('common.fields.imConversationNumber.displayName')}}</label>
                  <div
                    class="form-view-row-content im-detail-number"
                  >
                    {{ item.conversationNumber }}
                  </div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.contact.displayName')}}</label>
                  <div class="form-view-row-content">{{ item.linkmanName }}</div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.phone.displayName')}}</label>
                  <div class="form-view-row-content">{{ item.phone }}</div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.imStartTime.displayName')}}</label>
                  <div class="form-view-row-content">
                    {{ item.startTime | formatDate }}
                  </div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.imCloseTime.displayName')}}</label>
                  <div class="form-view-row-content">
                    {{ item.endTime | formatDate }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="session-card" shadow="hover" v-if="_isShowTaskModule">
          <div slot="header" @click="expand('task')">
            <span
            ><i
              class="iconfont icon-nav-down toggle-up"
              :class="taskToggle ? 'is-reverse' : ''"
            ></i
            >{{
              taskList.length ? `${$t('im.imChat.components.seviceRecords.des2')}(${taskList.length})` : $t('im.imChat.components.seviceRecords.des2')
            }}</span
            >
          </div>
          <div v-show="showTask" class="list-wrap">
            <div
              v-for="item in taskList"
              :key="item.id"
              class="list-item"
              @click="goTaskDetail(item.id)"
            >
              <div class="list-content">
                <div class="form-view-row">
                  <label>{{$t('common.task.taskType')}}</label>
                  <div class="form-view-row-content">{{ item.templateName }}</div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.task.taskState')}}</label>
                  <div class="form-view-row-content">
                    <!-- <el-tag class="task-type-tag" effect="dark">{{item.state | fmt_state}}</el-tag> -->
                    <span
                      class="task-state"
                      :style="{
                        'background-color': taskStateColor(item).bgColor,
                        color: '#FFF',
                      }"
                    >
                      {{ taskStateText(item) }}
                    </span>
                  </div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.executorUser.displayName')}}</label>
                  <div class="form-view-row-content">
                    <template
                      v-if="isOpenData && item.staffId"
                    >
                      <open-data
                        type="userName"
                        :openid="item.staffId"
                      ></open-data>
                    </template>
                    <template v-else>
                      {{ item.displayName }}
                    </template>
                  </div>
                </div>
                <div
                  v-if="item.synergies && item.synergies.length"
                  class="form-view-row"
                >
                  <label>{{$t('common.fields.synergies.displayName')}}</label>
                  <div class="form-view-row-content">
                    <template v-if="isOpenData">
                      <template v-if="item.synergies.length < 4">
                        <open-data
                          v-for="synergy in item.synergies"
                          :key="synergy.staffId"
                          type="userName"
                          :openid="synergy.staffId"
                        ></open-data>
                      </template>
                      <template v-else>
                        <open-data
                          v-for="synergy in item.synergies"
                          :key="synergy.staffId"
                          type="userName"
                          :openid="synergy.staffId"
                        ></open-data
                        >{{$t('im.imChat.components.seviceRecords.des4', {data1:item.synergies.length})}}
                      </template>
                    </template>
                    <template v-else>
                      {{ fmt_synergies(item.synergies) }}
                    </template>
                  </div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.createTime.displayName')}}</label>
                  <div class="form-view-row-content">
                    {{ item.createTime | formatDate }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="session-card" shadow="hover">
          <div slot="header" @click="expand('event')">
            <span
            ><i
              class="iconfont icon-nav-down toggle-up"
              :class="eventToggle ? 'is-reverse' : ''"
            ></i
            >{{
              eventList.length ? `${$t('im.imChat.components.seviceRecords.des3')}(${eventList.length})` : $t('im.imChat.components.seviceRecords.des3')
            }}</span
            >
          </div>
          <div v-show="showEvent" class="list-wrap">
            <div
              v-for="item in eventList"
              :key="item.id"
              class="list-item"
              @click="goEventDetail(item.id)"
            >
              <div class="list-content">
                <div class="form-view-row">
                  <label>{{$t('common.event.eventType')}}</label>
                  <div class="form-view-row-content">{{ item.templateName }}</div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.event.eventState')}}</label>
                  <div class="form-view-row-content">
                    <!-- <el-tag class="task-type-tag" effect="dark">{{item.state | fmt_state}}</el-tag> -->
                    <span
                      class="task-state"
                      :style="{
                        'background-color': eventStateColor(item).bgColor,
                        color: '#FFF',
                      }"
                    >
                      {{ eventStateText(item) }}
                    </span>
                  </div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.executorUser.displayName')}}</label>
                  <div class="form-view-row-content">
                    <template v-if="isOpenData && item.executorStaffId">
                      <open-data
                        type="userName"
                        :openid="item.executorStaffId"
                      ></open-data>
                    </template>
                    <template v-else>
                      {{ item.executorName }}
                    </template>
                  </div>
                </div>
                <div
                  v-if="item.synergies && item.synergies.length"
                  class="form-view-row"
                >
                  <label>{{$t('common.fields.synergies.displayName')}}</label>
                  <div class="form-view-row-content">
                    <template v-if="isOpenData">
                      <open-data
                        v-for="synergy in item.synergies"
                        :key="synergy.staffId"
                        type="userName"
                        :openid="synergy.staffId"
                      ></open-data>
                    </template>
                    <template v-else>
                      {{ fmt_synergies(item.synergies) }}
                    </template>
                  </div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.createTime.displayName')}}</label>
                  <div class="form-view-row-content">
                    {{ item.createTime | formatDate }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="session-card" shadow="hover">
          <div slot="header" @click="expand('history')">
            <span
            ><i
              class="iconfont icon-nav-down toggle-up"
              :class="historyToggle ? 'is-reverse' : ''"
            ></i
            >{{
              historyList.length
                ? `${$t('im.imChat.components.seviceRecords.des5')}(${historyList.length})`
                : $t('im.imChat.components.seviceRecords.des5')
            }}</span
            >
          </div>
          <div v-show="showHistory" class="list-wrap">
            <div
              v-for="item in historyList"
              :key="item.id"
              class="list-item"
              @click="goHistoryDetail(item)"
            >
              <div class="list-content">
                <div class="form-view-row">
                  <label>{{$t('im.imChat.components.seviceRecords.des6')}}</label>
                  <div class="form-view-row-content">{{ item.agent }}</div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('im.imChat.components.seviceRecords.des7')}}</label>
                  <div class="form-view-row-content">
                    <template v-if="isOpenData && item.agentStaffId">
                      <open-data
                        type="userName"
                        :openid="item.agentStaffId"
                      ></open-data>
                    </template>
                    <template v-else>
                      <span>{{ item.agentName }}</span>
                    </template>
                  </div>
                </div>
                <div class="form-view-row">
                  <label>{{$t('common.fields.createTime.displayName')}}</label>
                  <div class="form-view-row-content">
                    {{ item.ring | formatDate }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </template>

      <template v-else>
        <div class="default">
          <div class="default-img">
            <img :src="noDataImage" alt="" />
          </div>
          <div class="default-msg">{{$t('common.base.tip.noData')}}</div>
        </div>
      </template>
    </template>
  </div>
</template>
<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { formatDate } from 'pub-bbx-utils';
import * as CallCenterApi from '@src/api/CallCenterApi';
import * as IMApi from '@src/api/ImApi';
import TaskStateEnum from '@model/enum/TaskStateEnum.ts';
import EventStateEnum from '@model/enum/EventStateEnum.ts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
/* version control mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'service-records',
  mixins: [VersionControlTaskMixin],
  props: {
    userDetail: {
      type: Object,
      default: () => ({}),
    },
    conversationId:{
      type:Number,
      default:null
    },
  },
  watch: {
    userDetail: {
      handler(newValue) {
        if (newValue && newValue.linkmanPhone) {
          this.linkmanPhone = newValue.linkmanPhone;
          this.getServiceRecordV2()
        }else{
          this.serviceList = []
          this.taskList = [];
          this.eventList = [];
          this.historyList = [];
        }
      },
    },
  },
  data() {
    return {
      noDataImage,
      isOpenData,
      linkmanPhone: '',
      sessionToggle: false,
      taskToggle: false,
      eventToggle: false,
      historyToggle: false,

      showSession: false,
      showTask: false,
      showEvent: false,
      showHistory: false,
      serviceList:[],
      taskList: [],
      eventList: [],
      historyList: [],
      loadPage:true,
    };
  },
  filters: {
    formatDate(value) {
      return formatDate(value, 'YYYY-MM-DD HH:mm:ss');
    },
  },
  computed: {
    showCard() {
      
      const isHaveServiceList = this.serviceList.length
      const isHaveTaskList = this.taskList.length
      const isHaveEventList = this.eventList.length
      const isHaveHistoryList = this.historyList.length
      
      return (
        isHaveServiceList ||
        isHaveEventList ||
        isHaveHistoryList ||
        (this._isShowTaskModule && isHaveTaskList)
      )
      
    }
  },
  async mounted(){
    await this.getServiceRecordV2()
    this.loadPage = false
  },
  methods: {
    taskStateText(task) {
      return TaskStateEnum.getNameForTask(task);
    },
    taskStateColor(task) {
      return TaskStateEnum.getColorForTask(task);
    },
    eventStateText(event) {
      return EventStateEnum.getNameForEvent(event);
    },
    eventStateColor(event) {
      return EventStateEnum.getColorForEvent(event);
    },
    async getServiceRecordV2(){
      const {code, data} = await IMApi.getServiceRecordV2({conversationId:this.conversationId})
      if(code == 0){
        this.serviceList = data?.serviceRecordImList ?? []
        this.taskList = data?.serviceRecordTaskList ?? []
        this.eventList = data?.serviceRecordEventList ?? []
        this.historyList = data?.serviceRecordCallList ?? []
      }else{
        this.serviceList = []
        this.taskList = [];
        this.eventList = [];
        this.historyList = [];
      }
    },
    goHistoryDetail(row) {
      
      if (!this.globalIsHaveCallCenterViewDetailAuth) return
      
      // 跳转到历史通话记录详情
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `callcenter_view_${row.id}`,
      //   title: '通话详情',
      //   close: true,
      //   url: `/setting/callcenter/view?id=${row.id}&phone=${row.dialPhone}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCallcenterView,
        key: row.id,
        params: `id=${row.id}&phone=${row.dialPhone}`,
        fromId
      })
    },
    goTaskDetail(id) {
      // 跳转到工单详情
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `task_view_${id}`,
      //   title: '工单详情',
      //   close: true,
      //   url: `/task/view/${id}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: id,
        fromId
      })
    },
    goEventDetail(id) {
      // 跳转到事件详情
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `event_view_${id}`,
      //   title: '事件详情',
      //   close: true,
      //   url: `/event/view/${id}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: id,
        fromId
      })
    },
    expand(type) {
      switch (type) {
      case 'session':
        this.showTask = false;
        this.taskToggle = false;
        this.showEvent = false;
        this.eventToggle = false;
        this.showHistory = false;
        this.historyToggle = false;
        this.showSession = !this.showSession;
        this.sessionToggle = !this.sessionToggle;
        break;
      case 'task':
        this.showSession = false;
        this.sessionToggle = false;
        this.showEvent = false;
        this.eventToggle = false;
        this.showHistory = false;
        this.historyToggle = false;
        this.showTask = !this.showTask;
        this.taskToggle = !this.taskToggle;
        break;
      case 'event':
        this.showSession = false;
        this.sessionToggle = false;
        this.showTask = false;
        this.taskToggle = false;
        this.showHistory = false;
        this.historyToggle = false;
        this.showEvent = !this.showEvent;
        this.eventToggle = !this.eventToggle;
        break;
      case 'history':
        this.showSession = false;
        this.sessionToggle = false;
        this.showTask = false;
        this.taskToggle = false;
        this.showEvent = false;
        this.eventToggle = false;
        this.showHistory = !this.showHistory;
        this.historyToggle = !this.historyToggle;
        break;
      default:
        break;
      }
    },
    fmt_synergies(value = []) {
      const arr = [];
      value.length
        && value.forEach(item => {
          arr.push(item.displayName);
        });
      return arr.length < 4
        ? arr.join('，')
        : `${arr.join('，')}等${arr.count}人`;
    },
    goImDetail(conversationId) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `im_view_${conversationId}`,
      //   title: '会话详情',
      //   close: true,
      //   url: `/im/imDetail?id=${conversationId}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageImView,
        key: conversationId,
        params: `id=${conversationId}`,
        fromId
      })
    },
  },
  components: {},
};
</script>

<style lang="scss" scoped>
.service-record {
  overflow: auto;
  height: 100%;
  .el-card {
    margin-top: 8px;
  }
  ::v-deep .el-card__header {
    padding: 12px 20px;
    i {
      font-size: 12px !important;
    }
  }
  ::v-deep .el-card__body {
    padding: 0 !important;
  }
}
.im-detail-number {
  color: $color-primary-light-6;
}
.session-card {
  .list-wrap {
    max-height: 350px;
    overflow: auto;
    .list-item {
      padding: 10px 0;
      border-bottom: 1px solid #eee;
      cursor: pointer !important;
    }
  }
  .task-state-block {
    display: inline-block;
    width: auto;
    height: 22px;
    border-radius: 11px;
    margin-left: 8px;
    // margin-top: 5px;
    text-align: center;
    line-height: 22px;
    padding: 0 8px;

    &-overtime,
    &-approve {
      display: inline-block;
      color: #fff;
    }

    &-overtime {
      background-color: #f56c6c;
    }

    &-approve {
      background-color: #faae14;
    }
    &-ff {
      background-color: #ffa39e;
    }
  }

  .el-tag {
    margin-right: 5px;
    border-radius: 12px;
  }
  .task-type-tag {
    background: #1565c0;
    color: #fff;
  }

  .icon-nav-down {
    margin-right: 10px;
  }

  .toggle-up {
    display: inline-block;
    transition: transform 0.3s;
    transform: rotate(-90deg);
  }

  .is-reverse {
    transform: rotate(0deg) !important;
  }
}
.form-view-row {
  padding: 4px 12px;
  label {
    width: 90px;
    cursor: pointer;
  }
  .form-view-row-content {
    @include text-ellipsis();
    .task-state {
      border-radius: 12px;
      padding: 4px 10px;
      font-size: 12px;
    }
  }
}
.default {
  text-align: center;
  .default-img {
    margin-top: 80px;
    img {
      width: 160px;
      height: 160px;
    }
  }
  .default-msg {
    margin-top: 8px;
    color: $text-color-regular;
  }
}
</style>
